<template>
  <div class="tab">
    <cube-tab-bar :showSlider="true"
                  v-model="selectedLabel"
                  :data="tabs"
                  class="border-bottom-1px"
                  ref="tab"
                  :useTransition="false">
    </cube-tab-bar>
    <div class="slide-wrapper">
      <cube-slide :loop='false'
                  :auto-play='false'
                  :show-dots='false'
                  :initial-index="index"
                  @change="change"
                  ref="slide"
                  @scroll="scroll"
                  :options="options">
        <cube-slide-item v-for="(tab, index) in tabs"
                         :key="index">
          <compontents :is="tab.component"
                       :data="tab.data"
                       ref="component"></compontents>
        </cube-slide-item>
      </cube-slide>
    </div>
  </div>
</template>

<script>

export default {
  name: 'Tab',
  data () {
    return {
      options: {
        listenScroll: true, // 是否监控scroll事件
        probeType: 3, // 0 不派发scroll事件，1：非实时；2：滑动过程中；3：不仅在屏幕滑动的过程中，而且momentum 滚动动画运行过程中实时派发
        directionLockThreshold: 0
      },
      index: this.initialIndex
    }
  },
  props: {
    tabs: {
      type: Array,
      default () {
        return {}
      }
    },
    initialIndex: {
      type: Number,
      default: 0
    }
  },
  computed: {
    selectedLabel: {
      get () {
        return this.tabs[this.index].label
      },
      set (newVal) {
        this.index = this.tabs.findIndex((value) => {
          return value.label === newVal
        })
      }
    }
  },
  mounted () {
    this.change(this.index)
  },
  methods: {
    change (index) {
      this.index = index
      const component = this.$refs.component[index]
      component.fetch && component.fetch()
      // console.log(this.$refs.tab.$el.classList)
      // this.$refs.tab.$el.classList.value.remove('cube-tab_active')
      // this.$refs.tab.$el[index].classList.add('cube-tab_active')
    },
    scroll (pox) {
      // tabBar宽度
      const tabBarWidth = this.$refs.tab.$el.clientWidth
      // 滚动区域的宽度
      const slideWidth = this.$refs.slide.slide.scrollerWidth
      // 算出滚动的距离
      const transformX = -pox.x / slideWidth * tabBarWidth
      // 将滚动的距离赋值给下划线的滚动距离
      this.$refs.tab.setSliderTransform(transformX)
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~common/stylus/variable'
.tab
  display flex
  flex-direction column
  height 100%
  >>> .cube-tab
    padding 10px 0
  .slide-wrapper
    flex 1
    overflow hidden
</style>
